package com.qianxx.base;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.qianxx.utils.ToastUtil;
import com.qianxx.view.dialog.ExSweetAlertDialog;
import com.qianxx.view.loadingview.LoadingView;

import java.util.ArrayList;
import java.util.List;

import cn.pedant.SweetAlert.SweetAlertDialog;
import rx.functions.Action0;

/**
 * Created on 16/5/19 下午5:29.
 *
 * @author binwin20
 */
public abstract class LibBaseActivity extends AppCompatActivity {

    private static final int MY_PERMISSIONS_REQUEST = 1001;
    private static final String PACKAGE_URL_SCHEME = "package:"; // 方案
    private static final int REQUEST_CODE_REQUEST_SETTING = 1027;

    private Action0 mPermissionAction;
    private String mPermissionDescription;
    private List<String> needPermissions = null; // 未获得的权限列表

    protected LoadingView mLoadingView = null;
    private SweetAlertDialog mDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public void toast(int res) {
        ToastUtil.getInstance().toast(res);
    }

    public void toast(String msg) {
        ToastUtil.getInstance().toast(msg);
    }

    public void showLoadingView(boolean cancelable) {
        if (mDialog == null) {
            mDialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE);
            mDialog.getProgressHelper().setBarColor(getResources().getColor(R.color.colorPrimary));
            mDialog.setTitleText("");
        }
        mDialog.setCancelable(cancelable);
        mDialog.show();
//        if (mLoadingView == null) {
//            mLoadingView = (LoadingView) findViewById(R.id.loading_view);
//        }
//        if (mLoadingView == null) {
//            Logger.e("bin-->", "LibBaseActivity#showLoadingView(): LoadingView 不存在");
//            return;
//        }
//        mLoadingView.show(fullScreen);
    }

    public void hideLoadingView() {
        if (mDialog != null) mDialog.dismiss();
//        if (mLoadingView != null) {
//            mLoadingView.hide();
//        }
    }

    public void requestPermission(String[] permissions, Action0 action, @StringRes int needPermissionDescription) {
        requestPermission(permissions, action, getResources().getString(needPermissionDescription));
    }

    /**
     * 添加 fragment
     *
     * @param idRes    容器ID
     * @param fragment 待添加的 fragment
     */
    protected void addFragment(@IdRes int idRes, Fragment fragment) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(idRes, fragment);
        ft.commit();
    }

    /**
     * 替换 fragment
     *
     * @param idRes    容器ID
     * @param fragment 待替换的 fragment
     */
    protected void replaceFragment(@IdRes int idRes, Fragment fragment) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(idRes, fragment);
        ft.commit();
    }

    /**
     * @param permissions               权限列表
     * @param action                    获得权限之后的回调
     * @param needPermissionDescription 需要这些权限的原因（当用户第一次拒绝之后，会提示这个原因）
     */
    public void requestPermission(String[] permissions, Action0 action, String needPermissionDescription) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                if (needPermissions == null)
                    needPermissions = new ArrayList<>();
                needPermissions.add(permission);
            }
        }
        if (needPermissions == null) {  // 已经获得权限，直接执行
            action.call();
            return;
        }
        boolean needRationale = false; // 是否需要权限的原因。当申请的权限被用户拒绝之后，再次申请时会提示
        for (String p : needPermissions) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, p)) {
                needRationale = true;
                break;
            }
        }

        mPermissionAction = action;  // 获得权限之后的回调
        mPermissionDescription = needPermissionDescription;  // 申请权限的描述信息

        if (needRationale) { // 提示之后申请权限
            new ExSweetAlertDialog(this, ExSweetAlertDialog.AlertDialogType.NORMAL_TYPE)
                    .setTitleText("权限申请")
                    .setContentText(needPermissionDescription)
                    .setConfirmClickListener(dialog -> {
                        ActivityCompat.requestPermissions(this,
                                needPermissions.toArray(new String[0]),
                                MY_PERMISSIONS_REQUEST);
                        dialog.dismissWithAnimation();
                    }).show();
        } else { // 直接申请权限
            ActivityCompat.requestPermissions(this,
                    needPermissions.toArray(new String[0]),
                    MY_PERMISSIONS_REQUEST);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]
            grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_PERMISSIONS_REQUEST) {
            boolean allGranted = true;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allGranted = false;
                }
            }
            if (allGranted) {  // 已获得全部权限
                mPermissionAction.call();
            } else {  // 未获得权限，提示是否打开设置页面
                new ExSweetAlertDialog(this, ExSweetAlertDialog.AlertDialogType.ERROR_TYPE)
                        .setTitleText("权限申请失败")
                        .setContentText(mPermissionDescription + "\n是否前往设置？")
                        .setCancelText("取消")
                        .setConfirmText("确认")
                        .setConfirmClickListener(dialog -> {
                            startAppSettings();
                            dialog.dismissWithAnimation();
                        })
                        .setCancelClickListener(dialog -> {
                            dialog.dismissWithAnimation();
                        }).show();
            }
            return;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_REQUEST_SETTING) {
            List<String> list = new ArrayList<>();
            for (String permission : needPermissions) {
                if (ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_DENIED) {
                    list.add(permission);
                }
            }
            if (list.size() > 0) {
                onRequestPermissionFailed(list.toArray(new String[list.size()]));
            } else {
                mPermissionAction.call();
            }
        }
    }

    /**
     * 未获取到的权限回调
     *
     * @param permissions 未获取到的权限列表
     */
    protected void onRequestPermissionFailed(String[] permissions) {

    }

    private void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse(PACKAGE_URL_SCHEME + this.getPackageName()));
        this.startActivityForResult(intent, REQUEST_CODE_REQUEST_SETTING);
    }

    public void visible(View... views) {
        for (int i = 0; i < views.length; i++) {
            views[i].setVisibility(View.VISIBLE);
        }
    }

    public void invisible(View... views) {
        for (int i = 0; i < views.length; i++) {
            views[i].setVisibility(View.INVISIBLE);
        }
    }

    public void gone(View... views) {
        for (int i = 0; i < views.length; i++) {
            views[i].setVisibility(View.GONE);
        }
    }

}
